package com.jackrain.nea.fc.vp.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.common.PostHandleEvent;
import com.jackrain.nea.config.Resources;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.cp.api.ChrusersWebQueryCmd;
import com.jackrain.nea.fc.utils.Constants;
import com.jackrain.nea.fc.utils.ObjectToUtil;
import com.jackrain.nea.fc.utils.UserInformation;
import com.jackrain.nea.fc.vp.api.CvipSearchCmd;
import com.jackrain.nea.fc.vp.api.ViewCvipinteftpSaveCmd;
import com.jackrain.nea.fc.vp.mapper.ViewCvipinteftpMapper;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.QueryCmd;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySessionImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * POS零售累计积分
 *
 * @author xuxinshuai
 * @date 2017/11/13
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "vp")
public class ViewCvipinteftpSaveCmdImpl extends CommandAdapter implements ViewCvipinteftpSaveCmd {

    @Reference(version = "2", group = "cp")
    private QueryCmd queryCmd;

    @Reference(version = "1.0", group = "cp")
    private ChrusersWebQueryCmd chrusersWebQueryCmd;
    @Reference(version = "1.0", group = "vp")
    private CvipSearchCmd cvipSearchCmd;

    private Logger accesLogger = LoggerFactory.getLogger(Constants.ACCESS_PARAM_LOGGER);

    @Autowired
    PostHandleEvent postHandleEvent;

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {

        ValueHolder vh = new ValueHolder();
        ViewCvipinteftpMapper viewCvipinteftpMapper = ApplicationContextHandle.getBean(ViewCvipinteftpMapper.class);
        JSONObject jsonObject = null;
        try {
            jsonObject = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        } catch (Exception e) {
            e.printStackTrace();
            throw new NDSException("参数格式错误");
        }
        log.info("ViewCvipinteftpSaveCmdImpl--jsonObject-->{}",jsonObject);

//        log.debug("-----------积分调整参数----------" + jsonObject);
        JSONArray dataArray = jsonObject.getJSONArray("data");
        User user = chrusersWebQueryCmd.getUser(UserInformation.USER_NAME);//add by wwx

        for (int i = 0; i < dataArray.size(); i++) {

            JSONObject param = dataArray.getJSONObject(i);
            String cardid = param.getString("VP_C_VIP_ID");
            String VP_C_VIPTYPEGROUP_ID = param.getString("VP_C_VIPTYPEGROUP_ID");
            String INTEADJ = param.getString("INTEADJ");
            String BILLDATE = param.getString("BILLDATE");
            if (ObjectToUtil.isNullOREmpty(cardid)) {
                throw new NDSException("P_C_VIP_ID不能为空！");
            }
            if (ObjectToUtil.isNullOREmpty(VP_C_VIPTYPEGROUP_ID)) {
                throw new NDSException("VP_C_VIPTYPEGROUP_ID不能为空！");
            }
            if (ObjectToUtil.isNullOREmpty(INTEADJ)) {
                throw new NDSException("INTEADJ不能为空！");
            }
            if (ObjectToUtil.isNullOREmpty(BILLDATE)) {
                throw new NDSException("BILLDATE不能为空！");
            }
            Long vipGropuID = viewCvipinteftpMapper.selecttypegroupid(VP_C_VIPTYPEGROUP_ID);
            //------------------------查询VIP档案ID-----------------
            JSONObject vipSearchJson = new JSONObject();
            JSONObject fixedcolumnsJson = new JSONObject();
            fixedcolumnsJson.put("ACC.ECODES", cardid);
            fixedcolumnsJson.put("ACC.VP_C_VIPTYPEGROUP_ID", vipGropuID);
            JSONArray searchTypeArray = new JSONArray();
            JSONObject ecodeName = new JSONObject();
            ecodeName.put("name", "ACC.ECODES");
            ecodeName.put("type", "exact");
            searchTypeArray.add(ecodeName);
            JSONObject vipTypeName = new JSONObject();
            vipTypeName.put("name", "ACC.VP_C_VIPTYPEGROUP_ID");
            vipTypeName.put("type", "exact");
            searchTypeArray.add(vipTypeName);
            vipSearchJson.put("fixedcolumns", fixedcolumnsJson);
            vipSearchJson.put("searchtype", searchTypeArray);
            QuerySessionImpl querySession = new QuerySessionImpl(user);
            DefaultWebEvent event = new DefaultWebEvent("test", new HashMap());
            event.put("param", vipSearchJson);
            querySession.setEvent(event);
            ValueHolder vipValue = cvipSearchCmd.execute(querySession);
            JSONObject vipJson = vipValue.toJSONObject();
//            log.info("vipJson:" + vipJson);

            if (null == vipJson || (!vipJson.containsKey("IDS"))) {
                throw new NDSException("未查询到VIPID");
            }
            JSONArray idsArray = vipJson.getJSONArray("IDS");
            if (idsArray.size() != 1) {
                throw new NDSException("IDS未查询到或存在多条   IDS.SIZE:" + idsArray.size());
            }
            Long vipid = idsArray.getLong(0);
            if (vipid == null) {
                throw new NDSException("VIP档案不存在");
            }
            JSONObject insertJo = new JSONObject();
            insertJo.put("VP_C_VIP_ID", vipid);
            insertJo.put("VP_C_VIPTYPEGROUP_ID", vipGropuID);
            String cpstoreid = param.getString("CP_C_STORE_ID");
            Long distrib = null;
            if (!ObjectToUtil.isNullOREmpty(cpstoreid)) {

                try {
                    HashMap hashMap = new HashMap();
                    hashMap.put("tableName", "CP_C_STORE");
                    hashMap.put("fields", "ID,CP_C_DISTRIB_ID");
                    JSONObject whereJo = new JSONObject();
                    whereJo.put("ECODE", cpstoreid);
                    hashMap.put("whereKeys", whereJo);
                    hashMap.put("type", HashMap.class);
                    HashMap result = (HashMap) queryCmd.queryTable(hashMap);
                    if (result != null) {
                        if (result.containsKey("ID")) {
                            Long storeid = (Long) result.get("ID");
                            insertJo.put("CP_C_STORE_ID", storeid);
                        }
                        if (result.containsKey("CP_C_DISTRIB_ID")) {
                            distrib = (Long) result.get("CP_C_DISTRIB_ID");
                        }
                    }
                } catch (Exception e) {
                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    e.printStackTrace(pw);
                    throw new NDSException("跨库查询查询店仓ID和CP_C_DISTRIB_ID报错：" + sw.toString());
                }

            }
            String psskuid = param.getString("PS_C_SKU_ID");
            if (!ObjectToUtil.isNullOREmpty(psskuid)) {

                try {
                    HashMap hashMap = new HashMap();
                    hashMap.put("tableName", "PS_C_SKU");
                    hashMap.put("fields", "ID,PS_C_PRO_ID");
                    JSONObject whereJo = new JSONObject();
                    whereJo.put("ECODE", psskuid);
                    whereJo.put("CP_C_DISTRIB_ID", distrib);
                    hashMap.put("whereKeys", whereJo);
                    hashMap.put("type", HashMap.class);
//                    log.debug("hashmap参数" + hashMap);
                    HashMap result = (HashMap) queryCmd.queryTable(hashMap);
//                    log.debug("result参数" + result);
                    if (result != null) {
                        if (result.containsKey("ID")) {
                            Long skuid = (Long) result.get("ID");
                            insertJo.put("PS_C_SKU_ID", skuid);
                        }
                        if (result.containsKey("PS_C_PRO_ID")) {
                            Long proid = (Long) result.get("PS_C_PRO_ID");
                            insertJo.put("PS_C_PRO_ID", proid);
                        }
                    }
                } catch (Exception e) {

                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    e.printStackTrace(pw);
                    throw new NDSException("跨库查询查询条码ID和PS_C_PRO_ID报错：" + sw.toString());
                }

            }
            String inteadj = param.getString("INTEADJ");
            if (!ObjectToUtil.isNullOREmpty(inteadj)) {
                insertJo.put("INTEADJ", param.getDoubleValue("INTEADJ"));
            }
            String billdate = param.getString("BILLDATE");
            if (!ObjectToUtil.isNullOREmpty(billdate)) {

                try {
                    Date scoreDate = TypeUtils.castToDate(billdate);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
                    String sc = simpleDateFormat.format(scoreDate);
                    insertJo.put("BILLDATE", sc);
                } catch (Exception e) {
                    throw new NDSException("日期格式错误！");
                }

            }
            insertJo.put("INTETYPE", param.getString("INTETYPE"));
            insertJo.put("REMARK", param.getString("REMARK"));
            insertJo.put("DOCNO", param.getString("DOCNO"));
            insertJo.put("sourceId", param.getString("sourceId"));
            String amtactual = param.getString("AMT_ACTUAL");
            if (!ObjectToUtil.isNullOREmpty(amtactual)) {
                insertJo.put("AMT_ACTUAL", param.getString("AMT_ACTUAL"));
            }

            //创建时间
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            insertJo.put("CREATIONDATE", param.getString("BILLDATE"));
            //修改时间
            insertJo.put("MODIFIEDDATE", param.getString("BILLDATE"));

            event.put("param", insertJo);
            querySession.setEvent(event);
//            log.debug("Cvipinteftp参数" + insertJo);
            accesLogger.info("ViewCvipinteftpSaveCmdImpl--insertJo-->{}",insertJo);

            try {
//                ValueHolder valueHolder = cvipinteftpAddCmd.execute(querySession);

                JSONObject vipinteftpJson = postHandleEvent.executePostHandle(insertJo, querySession, event, "add");

//                JSONObject vipinteftpJson = valueHolder.toJSONObject();
                if (vipinteftpJson.containsKey("code") && (vipinteftpJson.getLong("code") == -1)) {
                    throw new NDSException("调用标准服务错误:" + vipinteftpJson.getString("message"));
                }
                vh.put("data", vipinteftpJson);
            } catch (Exception e) {

                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);
                throw new NDSException("调用标准服务错误" + sw.toString());

            }
        }
        vh.put("status", 0);
        vh.put("message", Resources.getMessage("success"));
        return vh;
    }
}
